﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Books.Common;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Books.ViewModel;
using System.Threading.Tasks;
using Books.Controls;
using Windows.Storage;
using Windows.Media;
using System.Text;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using Microsoft.Practices.ServiceLocation;
using Services.Model;
using System.Diagnostics;
using Books.SQLite;
using Windows.UI.Popups;
using Windows.UI.Xaml.Automation;

// The Group Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234229

namespace Books.View
{
    /// <summary>
    /// A page that displays an overview of a single group, including a preview of the items
    /// within the group.
    /// </summary>
    public sealed partial class DetailPage : Page
    {
        private NavigationHelper navigationHelper;
        /// <summary>
        /// Timer used to update the media position Slider.
        /// </summary>
        private DispatcherTimer timer;
        IReadOnlyList<StorageFile> FilesPlay;
        private static int indexPlayFile;
        /// <summary>
        /// Tracks whether the user is currently interacting with the media position Slider.
        /// </summary>
        private bool sliderPressed = false;
        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        SystemMediaTransportControls systemMediaControls = null;
        bool SystemMediaTransportControlsInitialized = false;
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        public DetailPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            TimelineSlider.AddHandler(Slider.PointerPressedEvent, new PointerEventHandler(TimelineSlider_PointerPressed), true);
            TimelineSlider.AddHandler(Slider.PointerReleasedEvent, new PointerEventHandler(TimelineSlider_PointerReleased), true);
            this.Loaded += DetailPage_Loaded;


        }

        async void DetailPage_Loaded(object sender, RoutedEventArgs e)
        {
            var data = await dataContext.GetData();
            if (data != null)
            {
                dataContext.DataBooksDetail = data;
                dataContext.GetRecommendBooks();
            }
            DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
            App.Player = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);
            if (App.Player != null)
            {
                App.Player.CurrentStateChanged += MediaElement_CurrentStateChanged;
                App.Player.MediaOpened += MediaElement_MediaOpened;
                App.Player.MediaEnded += MediaElement_MediaEnded;
            }
        }
        public async Task AddControl(StorageFile file)
        {

            timer = new DispatcherTimer();
            ChapterName.Text = "Playing chapter " + file.DisplayName;
            // Ensure a file was selected
            if (file != null)
            {
                MediaPlaybackType mediaPlaybackType;
                if ((file.FileType == ".mp4") || (file.FileType == ".wmv"))
                {
                    mediaPlaybackType = MediaPlaybackType.Video;
                }
                else
                {
                    mediaPlaybackType = MediaPlaybackType.Music;
                }

                // Inform the system transport controls of the media information
                if (!(await systemMediaControls.DisplayUpdater.CopyFromFileAsync(mediaPlaybackType, file)))
                {
                    //  Problem extracting metadata- just clear everything
                    systemMediaControls.DisplayUpdater.ClearAll();
                }
                systemMediaControls.DisplayUpdater.Update();
            }
            await SetMediaElementSourceAsync(file);
        }
        string FormatTimeSpan(TimeSpan timeSpan)
        {
            var sb = new StringBuilder();

            if (timeSpan < TimeSpan.Zero)
            {
                sb.Append('-');

                timeSpan = -timeSpan;
            }

            if (timeSpan.Days > 1)
                sb.AppendFormat(timeSpan.ToString(@"%d\."));

            sb.Append(timeSpan.ToString(@"hh\:mm\:ss"));

            return sb.ToString();
        }
        /// <summary>
        /// Handler for the system transport controls button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            switch (e.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Play();
                    });
                    break;

                case SystemMediaTransportControlsButton.Pause:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Pause();
                    });
                    break;

                case SystemMediaTransportControlsButton.Stop:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Stop();
                    });
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// Handler for the media element state change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            SystemMediaTransportControls systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            switch (App.Player.CurrentState)
            {
                default:
                case MediaElementState.Closed:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Resume");
                    RewindButton.IsEnabled = false;
                    ForwardButton.IsEnabled = false;
                    PauseButton.IsEnabled = false;
                    StopButton.IsEnabled = false;
                    PreviousButton.IsEnabled = false;
                    NextButton.IsEnabled = false;
                    break;

                case MediaElementState.Opening:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Changing;
                    break;

                case MediaElementState.Buffering:
                case MediaElementState.Playing:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Playing;
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Pause");
                    RewindButton.IsEnabled = true;
                    ForwardButton.IsEnabled = true;
                    StopButton.IsEnabled = true;
                    PauseButton.IsEnabled = true;
                    PreviousButton.IsEnabled = true;
                    NextButton.IsEnabled = true;
                    txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
                    break;

                case MediaElementState.Paused:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Paused;
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Resume");
                    PreviousButton.IsEnabled = true;
                    NextButton.IsEnabled = true;
                    RewindButton.IsEnabled = true;
                    PauseButton.IsEnabled = true;
                    ForwardButton.IsEnabled = true;
                    StopButton.IsEnabled = true;
                    break;

                case MediaElementState.Stopped:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
                    break;
            }
        }
        private BookDetailViewModel dataContext
        {
            get { return (BookDetailViewModel)DataContext; }
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {

        }
        public async Task SetMediaElementSourceAsync(StorageFile file)
        {
            SetupTimer();
            var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            App.Player.SetSource(stream, file.ContentType);
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => App.Player.Play());

        }
        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
            // Handle events from system transport contrtols when playing background-capable media
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;
            SystemMediaTransportControlsInitialized = true;
            //SetupTimer();
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
        }
        private void TimelineSlider_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            if (sliderPressed)
            {
                App.Player.Position = TimeSpan.FromSeconds(TimelineSlider.Value);
                sliderPressed = false;
            }
        }

        private void TimelineSlider_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            sliderPressed = true;
        }

        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            App.Player.PlaybackRate = 1.0;
            App.Player.Play();
            SetupTimer();
        }
        private void SetupTimer()
        {
            if (timer == null)
                timer = new DispatcherTimer();
            if (!timer.IsEnabled)
            {
                timer.Interval = TimeSpan.FromSeconds(1.0);
                timer.Tick += Timer_Tick;
                timer.Start();
            }
        }

        private void Timer_Tick(object sender, object e)
        {
            // Don't update the Slider's position while the user is interacting with it
            if (!sliderPressed)
            {
                TimelineSlider.Value = App.Player.Position.TotalSeconds;
            }
            Runtime.Text = FormatTimeSpan(App.Player.Position);
            txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
        }
        private double CalculateSliderFrequency(TimeSpan timevalue)
        {
            // Calculate the slider step frequency based on the timespan length
            double stepFrequency = 1;

            if (timevalue.TotalHours >= 1)
            {
                stepFrequency = 60;
            }
            else if (timevalue.TotalMinutes > 30)
            {
                stepFrequency = 30;
            }
            else if (timevalue.TotalMinutes > 10)
            {
                stepFrequency = 10;
            }
            else
            {
                stepFrequency = Math.Round(timevalue.TotalSeconds / 100, MidpointRounding.AwayFromZero);
            }

            return stepFrequency;
        }
        private void PauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
            {
                App.Player.Pause();
                MediaControl.IsPlaying = false;
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Resume");
            }
            else
            {
                App.Player.Play();
                MediaControl.IsPlaying = true;
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Pause");
            }

        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            TimelineSlider.Value = 0;
            App.Player.Stop();
            PauseButton.Content = "";
            AutomationProperties.SetName(PauseButton, "Pause");
        }

        private void RewindButton_Click(object sender, RoutedEventArgs e)
        {

            if (App.Player.Position > new TimeSpan(0, 1, 0))
            {
                App.Player.Position = App.Player.Position.Add(new TimeSpan(0, -1, 0));
            }
            else
            {
                App.Player.Position = new TimeSpan(0);
            }
        }

        private void ForwardButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Player.Position < App.Player.NaturalDuration.TimeSpan.Add(new TimeSpan(0, -1, 0)))
            {
                App.Player.Position = App.Player.Position.Add(new TimeSpan(0, 1, 0));
            }
        }
        private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            //txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
            // Set slider maximum to the media's duration in seconds
            TimelineSlider.Maximum = Math.Round(App.Player.NaturalDuration.TimeSpan.TotalSeconds, MidpointRounding.AwayFromZero);
            TimelineSlider.StepFrequency = CalculateSliderFrequency(App.Player.NaturalDuration.TimeSpan);
            SetupTimer();
        }

        private async void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            timer.Tick -= Timer_Tick;

            TimelineSlider.Value = 0.0;
            //if (indexPlayFile < FilesPlay.Count)
            //    indexPlayFile++;
            //AddControl(FilesPlay[indexPlayFile - 1]);
            await NextChapter();
        }
        #endregion
        private IHandleDownLoadFile handleDownLoadFile
        {
            get { return ServiceLocator.Current.GetInstance<IHandleDownLoadFile>(); }
        }
        private void DownloadAllFile(object sender, RoutedEventArgs e)
        {
            if (dataContext.DataBooksDetail.chapter_list.Count > 0)
            {
                foreach (var chapter in dataContext.DataBooksDetail.chapter_list)
                {
                    if (!chapter.IsDownload)
                    {
                        var items = this.ListDataChapter.ContainerFromItem(chapter) as ListViewItem;
                        var getControl = items.ContentTemplateRoot as DownloadChapter;
                        var listChapter = new List<ChapterList>();
                        listChapter.Add(chapter);
                        getControl.DownloadAll.Execute(listChapter);
                    }

                }
            }
            else
            {
                MessageDialog mesage = new MessageDialog("Chapter not found");
                mesage.ShowAsync();
            }
            //App.rootFrame.Navigate(typeof(DownloadFilesDetail));
            handleDownLoadFile.DownloadAll.Execute(dataContext.DataBooksDetail.chapter_list);
        }
        private async void ListDataChapter_ItemClick(object sender, ItemClickEventArgs e)
        {
            var itemSelect = e.ClickedItem as ChapterList;
            if (itemSelect.IsDownload)
            {
                var checkExitsFileDownloadComplete = ManagerFilesDownloadComplete.CheckExitsFolder(dataContext.DataBooksDetail.book_detail.book_id);
                if (checkExitsFileDownloadComplete)
                {
                    var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(dataContext.DataBooksDetail.book_detail.book_id);
                    var getListFile = await getFolder.GetFilesAsync();
                    if (getListFile.Count > 0)
                    {
                        indexPlayFile = int.Parse(itemSelect.chapter_no);
                        try
                        {
                            FilesPlay = getListFile;
                            var getItem = FilesPlay[indexPlayFile - 1];
                            AddControl(getItem);
                        }
                        catch (Exception ex)
                        { return; }
                    }

                }
            }
            else
            {
                var items = this.ListDataChapter.ContainerFromItem(e.ClickedItem) as ListViewItem;
                var getControl = items.ContentTemplateRoot as DownloadChapter;
                var listChapter = new List<ChapterList>();
                listChapter.Add(itemSelect);
                getControl.DownloadAll.Execute(listChapter);
            }

        }
        private async void Newest_ItemClick(object sender, ItemClickEventArgs e)
        {
            var data = e.ClickedItem as BookList;
            //HandleInAppPurchase purchase = new HandleInAppPurchase();
            //#if DEBUG
            //            var isPurchaseSuccess = await purchase.LoadInAppPurchaseProxyFileAsync(data.book_id);
            //#else
            //            var isPurchaseSuccess = await purchase.LoadInAppPurchaseAsync(data.book_id);
            //#endif
            //            if (isPurchaseSuccess)
            //            {
            dataContext.SetDataBookDetail(data.book_id, GetDeviceId.GetHardwareId());
            dataContext.DataBooksDetail = await dataContext.GetData();

            //}
        }

        private async void PreviousButton_Click(object sender, RoutedEventArgs e)
        {
            var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(dataContext.DataBooksDetail.book_detail.book_id);
            var getListFile = await getFolder.GetFilesAsync();
            if (getListFile.Count > 0)
            {
                FilesPlay = getListFile;
                if (indexPlayFile >= 2)
                {
                    indexPlayFile--;
                    await AddControl(FilesPlay[indexPlayFile - 1]);
                }

                else
                {
                    MessageDialog message = new MessageDialog("End list chapter");
                    message.ShowAsync();
                }

            }
        }

        private async void NextButton_Click(object sender, RoutedEventArgs e)
        {
            await NextChapter();
        }
        private async Task NextChapter()
        {
            var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(dataContext.DataBooksDetail.book_detail.book_id);
            var getListFile = await getFolder.GetFilesAsync();
            if (getListFile.Count > 0)
            {
                FilesPlay = getListFile;
                if (indexPlayFile < FilesPlay.Count)
                {
                    indexPlayFile++;
                    await AddControl(FilesPlay[indexPlayFile - 1]);
                }

                else
                {
                    MessageDialog message = new MessageDialog("End list chapter");
                    message.ShowAsync();
                }
            }
        }
    }

}
